package com.jugheadzhou.auth.core.message.producer.config;

import com.jugheadzhou.auth.core.message.producer.meta.AuthRabbitMeta;
import com.jugheadzhou.auth.core.message.producer.sender.RabbitSender;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author jugheadzhou
 * @date 2021-12-01
 */
@Configuration
public class RabbitConfig {

    /**
     * 全局websocket连接的通信队列
     *
     * @return
     */
    @Bean
    public Queue wsDirectQueue() {
        // durable:是否持久化,默认是false,持久化队列：会被存储在磁盘上，当消息代理重启时仍然存在，暂存队列：当前连接有效
        // exclusive:默认也是false，只能被当前创建的连接使用，而且当连接关闭后队列即被删除。此参考优先级高于durable
        // autoDelete:是否自动删除，当没有生产者或者消费者使用此队列，该队列会自动删除。
        return QueueBuilder
                .durable(AuthRabbitMeta.WS_GLOBAL.getQueueName())
                // 声明当前队列绑定的死信交换机
                .deadLetterExchange(AuthRabbitMeta.WS_GLOBAL_DLX.getExchange())
                // 声明当前队列的死信路由键
                .deadLetterRoutingKey(AuthRabbitMeta.WS_GLOBAL_DLX.getRoutingKey())
                .build();
    }

    /**
     * 全局websocket连接的通信交换机
     *
     * @return
     */
    @Bean
    DirectExchange wsDirectExchange() {

        return ExchangeBuilder
                .directExchange(AuthRabbitMeta.WS_GLOBAL.getExchange())
                .durable(true)
                .build();
    }


    /**
     * 将队列和交换机绑定,并设置匹配键
     *
     * @return
     */
    @Bean
    Binding wsBindingDirect() {

        return BindingBuilder
                .bind(wsDirectQueue())
                .to(wsDirectExchange())
                .with(AuthRabbitMeta.WS_GLOBAL.getRoutingKey());
    }

    /**
     * 全局websocket连接的通信的死信交换机
     *
     * @return
     */
    @Bean
    public DirectExchange wsDlxExchange() {

        return ExchangeBuilder
                .directExchange(AuthRabbitMeta.WS_GLOBAL_DLX.getExchange())
                .durable(true)
                .build();
    }

    /**
     * 全局websocket连接的通信的死信队列
     *
     * @return
     */
    @Bean
    public Queue wsDlxQueue() {

        return QueueBuilder
                .durable(AuthRabbitMeta.WS_GLOBAL_DLX.getQueueName())
                .build();
    }

    /**
     * 死信队列绑定死信交换机
     *
     * @return
     */
    @Bean
    public Binding wsDlcBinding() {

        return BindingBuilder
                .bind(wsDlxQueue())
                .to(wsDlxExchange())
                .with(AuthRabbitMeta.WS_GLOBAL_DLX.getRoutingKey());
    }


    @Bean
    public RabbitSender rabbitSender(RabbitTemplate rabbitTemplate) {

        return new RabbitSender(rabbitTemplate);
    }


}
